import axios from 'axios'
import type { AxiosResponse, AxiosError } from 'axios'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useAuthStore } from '@/stores/auth'
import router from '@/router'

// 创建axios实例
const request = axios.create({
  baseURL: '/api',
  timeout: 30000,
  headers: {
    'Content-Type': 'application/json'
  }
})

// 请求拦截器
request.interceptors.request.use(
  (config) => {
    const authStore = useAuthStore()
    
    // 添加认证token
    if (authStore.token) {
      config.headers.Authorization = `Bearer ${authStore.token}`
    }
    
    return config
  },
  (error: AxiosError) => {
    console.error('请求错误:', error)
    return Promise.reject(error)
  }
)

// 响应拦截器
request.interceptors.response.use(
  (response: AxiosResponse) => {
    const { data } = response
    
    // 如果返回的是文件流，直接返回
    if (response.config.responseType === 'blob') {
      return response
    }
    
    // 统一处理响应数据
    if (data.success === false) {
      ElMessage.error(data.message || '请求失败')
      return Promise.reject(new Error(data.message || '请求失败'))
    }
    
    return data
  },
  async (error: AxiosError) => {
    const { response } = error
    const authStore = useAuthStore()
    
    if (response) {
      const { status, data } = response
      
      switch (status) {
        case 401:
          // 未授权，尝试刷新token
          if (authStore.token) {
            try {
              const refreshed = await authStore.refreshToken()
              if (refreshed && error.config) {
                // 重新发送原请求
                return request(error.config)
              }
            } catch (refreshError) {
              console.error('刷新token失败:', refreshError)
            }
          }
          
          // 跳转到登录页
          ElMessage.error('登录状态已过期，请重新登录')
          authStore.logout()
          router.push('/login')
          break
          
        case 403:
          ElMessage.error('没有权限访问该资源')
          break
          
        case 404:
          ElMessage.error('请求的资源不存在')
          break
          
        case 422:
          // 表单验证错误
          const errorMsg = (data as any)?.message || '表单验证失败'
          ElMessage.error(errorMsg)
          break
          
        case 500:
          ElMessage.error('服务器内部错误')
          break
          
        case 502:
        case 503:
        case 504:
          ElMessage.error('服务暂时不可用，请稍后重试')
          break
          
        default:
          const message = (data as any)?.message || error.message || '请求失败'
          ElMessage.error(message)
      }
    } else if (error.code === 'ECONNABORTED') {
      ElMessage.error('请求超时，请检查网络连接')
    } else if (error.message.includes('Network Error')) {
      ElMessage.error('网络连接失败，请检查网络设置')
    } else {
      ElMessage.error(error.message || '未知错误')
    }
    
    return Promise.reject(error)
  }
)

// 导出请求方法
export const api = {
  get: <T = any>(url: string, params?: object) => 
    request.get<T>(url, { params }),
    
  post: <T = any>(url: string, data?: object) => 
    request.post<T>(url, data),
    
  put: <T = any>(url: string, data?: object) => 
    request.put<T>(url, data),
    
  patch: <T = any>(url: string, data?: object) => 
    request.patch<T>(url, data),
    
  delete: <T = any>(url: string, params?: object) => 
    request.delete<T>(url, { params }),
    
  upload: (url: string, formData: FormData) => 
    request.post(url, formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    }),
    
  download: (url: string, params?: object) => 
    request.get(url, {
      params,
      responseType: 'blob'
    })
}

export default request